package com.th.therp.controller;

import com.th.therp.exception.BaseException;
import com.th.therp.pojo.emtity.Customer;
import com.th.therp.pojo.result.Result;
import com.th.therp.service.CustomerService;
import jakarta.validation.Valid;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 客户请求控制器
 */
@Log4j2
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    //查询全部客户
    @GetMapping("/page")
    @ResponseBody
    public Result<List<Customer>> list() {
        log.info("查询全部客户");
        List<Customer> customerList = customerService.list();
        return Result.success(customerList);
    }

    //新增客户
    @PostMapping()
    @ResponseBody
    public Result add(@Valid @RequestBody Customer customer,BindingResult bindingResult) {
        log.info("新增客户:{}",customer);
        if(bindingResult.hasErrors()){throw new BaseException("格式不正确");}
        customerService.add(customer);
        return Result.success();
    }

    //修改客户
    @PutMapping()
    @ResponseBody
    public Result update(@Valid @RequestBody Customer customer, BindingResult bindingResult) {
        log.info("修改用户:{}",customer);
        if(bindingResult.hasErrors()){throw new BaseException("格式不正确");}
        customerService.update(customer);
        return Result.success();
    }

    //删除客户
    @DeleteMapping()
    @ResponseBody
    public Result delete(@RequestParam List<Integer> ids) {
        log.info("删除用户:{}",ids);
        customerService.delete(ids);
        return Result.success();
    }
}